import { QueryTypes } from "sequelize";
import { sequelize } from "../lib/database.js";
import logger from "../lib/log4js.js";
import { WeightValueChecker } from './weight-value-checker.ts'
import { RuFormMapper } from "./ru-form.ts";
import { D3_TOP, USER_TYPES } from "../entity/common-defines.ts";
import { XlsxData } from "./xlsx-data.ts";
import { EvaProjectMapper } from "./eva-project.ts";


class ResultLeaderGroupMapper extends XlsxData {


	private formMapper: RuFormMapper = new RuFormMapper;
	private checker: WeightValueChecker = new WeightValueChecker;
	private projectMapper: EvaProjectMapper = new EvaProjectMapper;
	public async getResultData(project_id: string, test: boolean): Promise<SheetData> {
		const form: any = await this.formMapper.findOneByQuery({ where: { user_type: USER_TYPES.LEADER_GROUP } })
		const formId: string = form?.id;

		const added_value = await this.checker.findAddedScoreValue(project_id, formId);
		const sql = `
        -- 领导班子
select
	user_name,
	amount,
	round(sum(case when rule_name = '政治担当' then rule_vote_value end),2) as 政治担当,
	round(sum(case when rule_name = '社会责任' then rule_vote_value end),2) as 社会责任,
	round(sum(case when rule_name = '经营效益' then rule_vote_value end),2)as 经营效益,
	round(sum(case when rule_name = '管理效能' then rule_vote_value end),2) as 管理效能,
	round(sum(case when rule_name = '风险管控' then rule_vote_value end),2) as 风险管控,
	round(sum(case when rule_name = '科技创新' then rule_vote_value end),2) as 科技创新,
	round(sum(case when rule_name = '人才强企' then rule_vote_value end),2) as 人才强企,
	round(sum(case when rule_name = '深化改革' then rule_vote_value end),2) as 深化改革,
	round(sum(case when rule_name = '选人用人' then rule_vote_value end),2) as 选人用人,
	round(sum(case when rule_name = '基层党建' then rule_vote_value end),2) as 基层党建,
	round(sum(case when rule_name = '党风廉政' then rule_vote_value end),2) as 党风廉政,
	round(sum(case when rule_name = '团结协作' then rule_vote_value end),2) as 团结协作,
	round(sum(case when rule_name = '联系群众' then rule_vote_value end),2) as 联系群众
from
	(
	-- 第二层:票类分组
	select
		form_id,
		type_id,
		user_name,
		rule_name,
		sum(amount) amount,
		sum(type_vote_value) rule_vote_value
	from
		(
		--  第一层:获取指标分组
		select
			rfr.form_id,
			on2.type_id,
			on2.type_name,
			ea.rule_name,
			ea.user_name,
			sum(1) amount,
			(sum(convert(json_value(ifnull(ea.rule_value, '[0]'), '$[0]'), int))/sum(1)) * if(rfr.weight_value is null or rfr.weight_value =0,1,rfr.weight_value ) /100 type_vote_value
		from
			eva_answer ea
		inner join eva_project_owner epo on
			epo.project_id = ea.project_id
			and epo.id = ea.project_owner_id
		inner join owner_name on2 on
			on2.id = epo.owner_name_id
		inner join eva_project ep on ep.id=?	
		inner join ru_form_owner_type rfr on
			rfr.form_id = ea.rule_form_id
			and rfr.type_id = on2.type_id
			and rfr.group_type=ep.group_type
		where
		    ea.is_test is ?
			and ea.project_id = ?
			and ea.user_type = ?
			and ea.rule_form_id = ?
		group by		
			rule_id,    -- 所用规则 
			type_id     -- 主体类型
  ) twn
	group by
		twn.user_name ,
		twn.rule_name desc 
) ea_leader_group
group by
	user_name

        `;
		try {
			const result: Array<LeaderGroupResult> = await sequelize.query(sql, {
				replacements: [test, project_id, project_id, USER_TYPES.LEADER_GROUP, formId],
				type: QueryTypes.SELECT
			})
			if (result && result.length === 1) {

				const result2: Array<LeaderGroupResult> = result.map(({ user_name, amount, 政治担当, 社会责任, 经营效益, 管理效能, 风险管控, 科技创新, 人才强企, 深化改革,
					选人用人, 基层党建, 党风廉政, 团结协作, 联系群众 }) => (
					{
						user_name,
						amount,
						政治担当: 政治担当 + added_value,
						社会责任: 社会责任 + added_value,
						经营效益: 经营效益 + added_value,
						管理效能: 管理效能 + added_value,
						风险管控: 风险管控 + added_value,
						科技创新: 科技创新 + added_value,
						人才强企: 人才强企 + added_value,
						深化改革: 深化改革 + added_value,
						选人用人: 选人用人 + added_value,
						基层党建: 基层党建 + added_value,
						党风廉政: 党风廉政 + added_value,
						团结协作: 团结协作 + added_value,
						联系群众: 联系群众 + added_value
					}));
				const project: any = await this.projectMapper.findOne({ pk: project_id });
				return {
					title: `${project.object_group_name}-${project.ef_year}年${form.name}`,
					name: form.name,
					data: result2
				};
			}
		} catch (error) {
			logger.error(error);
		}
		return { data: [] };
	}

	async exportXlsxSheet(test: boolean, project_id: string, rowStart: number, index: number): Promise<SheetMeta> {
		const { title, name, data } = await this.getResultData(project_id, test);
		if (data.length === 0) {
			return { merges: [], data: [], name };
		}

		const result_data = [];
		result_data.push([`${index + 1}.${title}`, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "加权得分"]);
		const top_names = ["评价内容"];
		for (const [key, value] of Object.entries(D3_TOP)) {
			top_names.push(key);
			for (const vk of value.items) {
				top_names.push(" ");
			}
		}
		result_data.push(top_names);
		const child_names = ["评价指标"];
		for (const key in D3_TOP) {
			child_names.push("小计");
			for (const lkey of D3_TOP[key].items) {
				child_names.push(lkey);
			}
		}
		result_data.push(child_names);
		const child_data = ["内测得分"];
		const whole_value = [];
		for (const key in D3_TOP) {
			const item_value = D3_TOP[key];
			const keys = item_value.items;
			const nVal = keys.map((n, i) => data[0][n] * item_value.child_rate[i] / 100).reduce((a, b) => a + b);
			whole_value.push(nVal * item_value.rate / 100);
			child_data.push(nVal);
			for (const nkey of keys) {
				child_data.push(data[0][nkey]);
			}
		}
		const wv = whole_value.reduce((a, b) => a + b);
		child_data.push(wv);
		result_data.push(child_data);
		let mc = 1;
		const merges = [
			{ s: { c: 0, r: rowStart }, e: { c: 18, r: rowStart } },
			{ s: { c: 19, r: rowStart }, e: { c: 19, r: rowStart + 2 } },
		];
		for (const cary of Object.values(D3_TOP)) {
			//logger.debug(cary);
			merges.push({ s: { c: mc, r: rowStart + 1 }, e: { c: mc + cary.items.length, r: rowStart + 1 } });
			mc = mc + cary.items.length + 1;
		}
		//logger.info(merges);
		return { merges, data: result_data, name }
	}
}
export { ResultLeaderGroupMapper }